package com.tencent.wxcloudrun.util;

import com.alibaba.fastjson2.JSONObject;
import com.tencent.wxcloudrun.constant.RedisKeyConstant;
import com.tencent.wxcloudrun.domain.TUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Author ZhaoZiYin
 * @Date 2025/4/27
 * @Description Redis业务工具类
 */
@Slf4j
@Component
public class RedisBusiUtil {

    private static RedisUtil redisUtil;

    public RedisBusiUtil(RedisUtil redisUtil) {
        RedisBusiUtil.redisUtil = redisUtil;
    }

    /**
     * @Author: ZhaoZiYin
     * @Date: 2025/4/27
     * @Params: [userId]
     * @Return: TUser
     * @Description: 获取用户缓存信息
     */
    public static TUser getUserInfo(Long userId) {
        String userObjStr = redisUtil.get(RedisKeyConstant.getUserRedisKey(userId));
        if (StringUtils.hasLength(userObjStr)) {
            return JSONObject.parseObject(userObjStr, TUser.class);
        }
        return null;
    }

    /**
     * @Author: ZhaoZiYin
     * @Date: 2025/4/30
     * @Params: [user]
     * @Return: void
     * @Description: 保存用户缓存信息
     */
    public static void saveUserInfo(TUser user) {
        redisUtil.set(RedisKeyConstant.getUserRedisKey(user.getId()), JSONObject.toJSONString(user));
        redisUtil.set(RedisKeyConstant.getUserOpenIdRedisKey(user.getWxOpenId()), JSONObject.toJSONString(user));
    }

    /**
     * @Author: ZhaoZiYin
     * @Date: 2025/6/11
     * @Params: [wxOpenId]
     * @Return: TUser
     * @Description: 获取用户缓存信息
     */
    public static TUser getUserInfoByWxOpenId(String wxOpenId) {
        String userObjStr = redisUtil.get(RedisKeyConstant.getUserOpenIdRedisKey(wxOpenId));
        if (StringUtils.hasLength(userObjStr)) {
            return JSONObject.parseObject(userObjStr, TUser.class);
        }
        return null;
    }

}
